package Sort2017;

/**
 * 冒泡排序
 * Created by 雷文康 on 2017/12/22.
 */
public class BubbleSort {
    public static void main(String[] args) {
        int[] array = {3,8,4,6,7,2,5,9,1};
        bubbleSort3(array);
        for (int i = 0; i < array.length; i++){
            System.out.print(array[i]);
        }
    }
    /**
     * 简单冒泡排序 挨个比较
     * @param array
     */
    public static void bubbleSort1(int[]  array){
        if (array == null || array.length == 0) {
            return;
        }
        for (int i = 0 ; i < array.length - 1; i++) {
            for (int j = i + 1; j < array.length; j++) {
                if (array[i] > array[j]) {
                    int temp = array[i];
                    array[i] = array[j];
                    array[j] =  temp;
                }
            }
        }
    }

    /**
     * 交換冒泡排序 相邻比较
     * @param array
     */
    public static void bubbleSort2(int[]  array){
        if (array == null || array.length == 0) {
            return;
        }
        for (int i = 0 ; i < array.length - 1; i++) {
            for (int j = array.length - 1; j > i; j--) {
                if (array[j] < array[j-1]) {
                    int temp = array[j];
                    array[j] = array[j-1];
                    array[j-1] =  temp;
                }
            }
        }
    }

    /**
     * 交換冒泡排序升级版 对1,2,3,4,5,6,7,8,9类型，若没有交换，则说明已经有序
     * @param array
     */
    public static void bubbleSort3(int[]  array){
        if (array == null || array.length == 0) {
            return;
        }

        boolean flag = true;
        for (int i = 0 ; i < array.length - 1 && flag; i++) {
            flag = false;
            for (int j = array.length - 1; j > i; j--) {
                if (array[j] < array[j-1]) {
                    int temp = array[j];
                    array[j] = array[j-1];
                    array[j-1] =  temp;
                    flag = true;
                }
            }
        }
    }
}
